package com.dandelion.manager.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dandelion.commons.spring.SpringContextHolder;
import com.dandelion.commons.web.model.AjaxResponse;
import com.dandelion.commons.web.model.DataGrid;
import com.dandelion.manager.system.domain.ResourcePermit;
import com.dandelion.manager.system.repository.ResourcePermitMapper;
import com.dandelion.manager.system.service.ResourcePermitService;

@Service
public class ResourcePermitServiceImpl implements ResourcePermitService {
	
	@Autowired
	private ResourcePermitMapper mapper ;

	@Override
	public AjaxResponse add(ResourcePermit record) {
		this.mapper.insertSelective(record) ;
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}

	@Override
	public AjaxResponse delete(long id) {
		this.mapper.deleteByPrimaryKey(id) ;
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}
	
	@Override
	public AjaxResponse deleteBatch(Long[] ids) {
		this.mapper.deleteByPrimaryKeys(ids) ;
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}


	@Override
	public AjaxResponse update(ResourcePermit record) {
		this.mapper.updateByPrimaryKeySelective(record) ;
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}

	@Override
	public ResourcePermit get(long id) {
		return this.mapper.selectByPrimaryKey(id) ;
	}

	@Override
	public List<ResourcePermit> getAllList(ResourcePermit record) {
		return this.mapper.selectAllList(record);
	}
	
	@Override
	public DataGrid<ResourcePermit> datagrid(ResourcePermit conditions) {
		DataGrid<ResourcePermit> dg = new DataGrid<ResourcePermit>();

		Map<String, Object> conditionsMap = new HashMap<String, Object>();
		conditionsMap.put("record", conditions);
		conditionsMap.put("offset", dg.getOffset());
		conditionsMap.put("rows", dg.getPageSize());

		List<ResourcePermit> list = this.mapper.selectAllListPage(conditionsMap);
		int count = this.mapper.getCount(conditionsMap);
		dg.setRows(list);
		dg.setTotal(count);

		return dg;
	}

	@Override
	public void insertBatch(Long resourceId, List<Long> permitIds) {
		List<ResourcePermit> recordBatch = new ArrayList<ResourcePermit>();
		for (Long permitId : permitIds) {
			ResourcePermit r = new ResourcePermit() ;
			r.setResource_id(resourceId);
			r.setPermit_id(permitId);
			recordBatch.add(r) ;
		}
		this.mapper.insertBatch(recordBatch);
	}

	@Override
	public void deleteByResourceId(Long resourceId) {
		this.mapper.deleteByResourceId(resourceId);
	}
	
}
